#include "bg_path.h"
#include "bg_scene.h"

#include "graphics/graphics_util.h"

#include "font/font_manager.h"
#include "dd/dd_man.h"
#include "util/timer.h"				// log
#include "util/log.h"				// log
#include "util/common_macros.h"		// macros
#include "util/mmgr.h"		    
#include "script/scripthelper.h"

using namespace background;


BGPath::BGPath(int PathID, BGScene* pScene) :
	m_pScene(pScene),
	m_PathID(PathID)
{

}

BGPath::~BGPath()
{

}

void	BGPath::CreateFromSpline(const math::SplineCache2D& Spline)
{	
	m_Spline.Clear();
	for (int i=0; i<(int)Spline.GetNodeC(); i++)
	{
		m_Spline.InsertNode(Spline.GetNode(i)->Pos);
	}
}

bool	BGPath::IsLoop()
{
	if (m_Spline.GetNodeC() < 2) return false;

	math::Vec2	P1 = m_Spline.GetNode(0)->Pos;
	math::Vec2	P2 = m_Spline.GetNode(m_Spline.GetNodeC()-1)->Pos;
	float	Delta = (P2-P1).Magnitude();

	return Delta < 15 / (float)GraphicsUtil::WIDTH;	// delta
}


void	BGPath::RenderDebug(const math::Vec2& Offset, float Scale)
{
	dd::Manager::Instance().AddSpline2(&m_Spline, 0.01f, ColorRGBA(255, 255, 255, 100), false, m_pScene->GetOffset()*Scale);
	FontManager::Instance().Print(m_Spline.GetNode(0)->Pos - m_pScene->GetOffset(),"PATH_%i", m_PathID);
}

void	BGPath::Tick(float dt)
{
}

math::Vec2	BGPath::GetPos()
{
	math::Vec2	Pos = m_Spline.GetPos(0, 0.01f);
	math::Vec2	P;
	if (!m_Spline.SplineHitTest(Pos, &P, 10/(float)GraphicsUtil::WIDTH))
	{
		int j=0;
	}
	return Pos;
}

bool		BGPath::HitTest(const math::Vec2& Pos, float Radius)
{
	math::Vec2	P;
	return m_Spline.SplineHitTest(Pos, &P, Radius);
}


